package com.yang.config;

import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * @author yds
 * @program spring-boot-shiro
 * @description 自定义数据处理对象
 * @create 2020-10-22 11:18
 **/
public class UserRealm extends AuthorizingRealm {
    /***
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("授权=>doGetAuthorizationInfo");
        //给指定用户授予部分权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //添加对应的字符串权限  权限字符串建议每个用户拥有不同的权限表存放字符串
        info.addStringPermission("user:add");
        //返回对应的权限信息
        return info;
    }

    /***
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证=>doGetAuthenticationInfo");
        // 伪造一个username password ,常规操作从数据库里面查询
        String username="root";
        String password="123456";
        UsernamePasswordToken userToken=(UsernamePasswordToken)token;
        if(!userToken.getUsername().equals(username)){
            //  return null 意味抛出异常UnknownAccountException
            return null;
        }
        //密码认证 shiro做
        return new SimpleAuthenticationInfo("",password,"");
    }
}